package com.spider.spider;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.logging.LogEntries;
import org.openqa.selenium.logging.LogEntry;
import org.openqa.selenium.logging.LogType;
import org.openqa.selenium.logging.LoggingPreferences;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;

public class EleCookie {
    public static void main(String[] args) {
        QQAccount.accountMaps.forEach((o,v)->{
            try {
                Thread.sleep(5000);
                addCookie(o, v);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

    }

    private static void addCookie(String account ,String pwd) {

        System.setProperty("webdriver.chrome.driver", "C:\\Users\\Administrator\\Desktop\\chromedriver_win32\\chromedriver.exe");//chromedriver服务地址

        Map<String, Object> deviceMetrics = new HashMap<>();

        deviceMetrics.put("width", 360);

        deviceMetrics.put("height", 640);

        deviceMetrics.put("pixelRatio", 3.0);

        Map<String, Object> mobileEmulation = new HashMap<>();

        mobileEmulation.put("deviceMetrics", deviceMetrics);
        mobileEmulation.put("userAgent", "Mozilla/5.0 (Linux; Android 5.1; m1 metal Build/LMY47I; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/53.0.2785.49 Mobile MQQBrowser/6.2 TBS/043409 Safari/537.36 V1ANDSQ7.2.5744YYBD QQ/7.2.5.3305 NetType/WIFI WebP/0.3.0 Pixel/1080");

        ChromeOptions chromeOptions = new ChromeOptions();
        chromeOptions.setExperimentalOption("mobileEmulation", mobileEmulation);

        WebDriver driver = new ChromeDriver(chromeOptions);

        driver.get("https://h5.ele.me/hongbao/#hardware_id=&is_lucky_group=True&lucky_number=5&track_id=&platform=4&sn=29ef424ec3af0418&theme_id=2377&device_id=&refer_user_id=115092954");//打开指定的网站

        driver.findElement(By.id("u")).sendKeys(new String[]{account});//找到u元素的id，然后输入hello
        driver.findElement(By.id("p")).sendKeys(new String[]{pwd});//找到u元素的id，然后输入hello

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        driver.findElement(By.id("go")).click(); //点击按扭

        try {
            Thread.sleep(30000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        Set<Cookie> cookies = driver.manage().getCookies();
        String cookiesJson = JSONObject.toJSONString(cookies);
        System.out.println("cookieJson = \n" + cookiesJson);

        JavascriptExecutor jse = (JavascriptExecutor) driver;
        String cookie = (String) jse.executeScript("return document.cookie");
        System.out.println(cookie);
        callApiByPost(cookie);
        driver.manage().deleteAllCookies();
        driver.quit();
    }

    public static void callApiByPost(String cookie) {
        String url = "http://47.96.89.84:8208/user/cookie";
        CloseableHttpClient httpClient = null;
        String result = null;
        HttpPost post = null;

        try {
            httpClient = HttpClients.createDefault();
            post = new HttpPost(url);
            post.setHeader("Accept", "application/json, text/plain, */*");
            post.setHeader("Accept-Encoding", "gzip, deflate");
            post.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
            post.setHeader("X-User-Token", "0D18D0E401156E77A11478E2D24A3358593440D2FDC2B2A9AF4485C3BB15A7DF363A2C4055A26B8C731097A91947BEEADC35C905F712BDAFBB0FAA5E21B1644D");
    
            Map<String, String> map = new HashMap<>();
            map.put("value", cookie);
            map.put("application", "1");
    
            List<NameValuePair> list = new ArrayList<NameValuePair>();
            Iterator iterator = map.entrySet().iterator();
            while(iterator.hasNext()){
                Map.Entry<String,String> elem = (Map.Entry<String, String>) iterator.next();
                list.add(new BasicNameValuePair(elem.getKey(),elem.getValue()));
            }
            if(list.size() > 0){
                UrlEncodedFormEntity  entity = new UrlEncodedFormEntity(list);
                post.setEntity(entity);
            }
            HttpResponse response = httpClient.execute(post);
            if(response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity);
                    System.out.println(result);
                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }
    }

//    public static void main(String[] args) {
//        System.setProperty("webdriver.chrome.driver","C:\\Users\\Ruan\\Desktop\\chromedriver_win32\\chromedriver.exe");//chromedriver服务地址
//
//        Map<String, Object> deviceMetrics = new HashMap<>();
//
//        deviceMetrics.put("width", 360);
//
//        deviceMetrics.put("height", 640);
//
//        deviceMetrics.put("pixelRatio", 3.0);
//
//        Map<String, Object> mobileEmulation = new HashMap<>();
//
//        mobileEmulation.put("deviceMetrics", deviceMetrics);
//        mobileEmulation.put("userAgent", "Mozilla/5.0 (Linux; Android 5.1; m1 metal Build/LMY47I; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/53.0.2785.49 Mobile MQQBrowser/6.2 TBS/043409 Safari/537.36 V1ANDSQ7.2.5744YYBD QQ/7.2.5.3305 NetType/WIFI WebP/0.3.0 Pixel/1080");
//
//        ChromeOptions chromeOptions = new ChromeOptions();
//        chromeOptions.setExperimentalOption("mobileEmulation", mobileEmulation);
//
//        WebDriver driver = new ChromeDriver(chromeOptions);
//
//        String cookieJson = "[{\"domain\":\".ele.me\",\"expiry\":1609459199000,\"httpOnly\":false,\"name\":\"_utrace\",\"path\":\"/\",\"secure\":false,\"value\":\"4111722dafce254aa7c807c6d205edda_2018-08-19\"},{\"domain\":\".ele.me\",\"expiry\":4070880000000,\"httpOnly\":false,\"name\":\"snsInfo[101204453]\",\"path\":\"/\",\"secure\":false,\"value\":\"%7B%22city%22%3A%22%E6%B8%A9%E5%B7%9E%22%2C%22constellation%22%3A%22%22%2C%22eleme_key%22%3A%22c29e50779e4dc936325e04fb00e27218%22%2C%22figureurl%22%3A%22http%3A%2F%2Fqzapp.qlogo.cn%2Fqzapp%2F101204453%2F78620680E9F6BD2DCC536971FF26E043%2F30%22%2C%22figureurl_1%22%3A%22http%3A%2F%2Fqzapp.qlogo.cn%2Fqzapp%2F101204453%2F78620680E9F6BD2DCC536971FF26E043%2F50%22%2C%22figureurl_2%22%3A%22http%3A%2F%2Fqzapp.qlogo.cn%2Fqzapp%2F101204453%2F78620680E9F6BD2DCC536971FF26E043%2F100%22%2C%22figureurl_qq_1%22%3A%22http%3A%2F%2Fthirdqq.qlogo.cn%2Fqqapp%2F101204453%2F78620680E9F6BD2DCC536971FF26E043%2F40%22%2C%22figureurl_qq_2%22%3A%22http%3A%2F%2Fthirdqq.qlogo.cn%2Fqqapp%2F101204453%2F78620680E9F6BD2DCC536971FF26E043%2F100%22%2C%22gender%22%3A%22%E7%94%B7%22%2C%22is_lost%22%3A0%2C%22is_yellow_vip%22%3A%220%22%2C%22is_yellow_year_vip%22%3A%220%22%2C%22level%22%3A%220%22%2C%22msg%22%3A%22%22%2C%22nickname%22%3A%22%20%20%20%20%20%20%20%20%20%20%20%20%22%2C%22openid%22%3A%2278620680E9F6BD2DCC536971FF26E043%22%2C%22province%22%3A%22%E6%B5%99%E6%B1%9F%22%2C%22ret%22%3A0%2C%22vip%22%3A%220%22%2C%22year%22%3A%221994%22%2C%22yellow_vip_level%22%3A%220%22%2C%22name%22%3A%22%20%20%20%20%20%20%20%20%20%20%20%20%22%2C%22avatar%22%3A%22http%3A%2F%2Fthirdqq.qlogo.cn%2Fqqapp%2F101204453%2F78620680E9F6BD2DCC536971FF26E043%2F40%22%7D\"},{\"domain\":\".ele.me\",\"expiry\":4070880000000,\"httpOnly\":false,\"name\":\"ubt_ssid\",\"path\":\"/\",\"secure\":false,\"value\":\"l3nwtucsybygsl22syze8u5metlihh4j_2018-08-19\"},{\"domain\":\".h5.ele.me\",\"expiry\":4070880000000,\"httpOnly\":false,\"name\":\"perf_ssid\",\"path\":\"/\",\"secure\":false,\"value\":\"igke6kxquluux5mvfx0b98u0x4aacpbj_2018-08-19\"}]\n";
//
//        Set<Cookie> cookies = JSON.parseObject(cookieJson, new TypeReference<Set<Cookie>>(){});
////        Set<Cookie> cookies = (Set<Cookie>) JSONObject.parseObject(cookieJson);
//
//        driver.get("https://h5.ele.me/hongbao/#hardware_id=&is_lucky_group=True&lucky_number=5&track_id=&platform=4&sn=29ef424ec3af0418&theme_id=2377&device_id=&refer_user_id=115092954");//打开指定的网站
//
//        try {
//            for (Cookie cookie : cookies) {
//                driver.manage().addCookie(cookie);
//            }
//            driver.navigate().refresh();
//            driver.get("https://h5.ele.me/hongbao/#hardware_id=&is_lucky_group=True&lucky_number=5&track_id=&platform=4&sn=29ef424ec3af0418&theme_id=2377&device_id=&refer_user_id=115092954");//打开指定的网站
//        } catch (Exception e) {
//            driver.navigate().refresh();
//            e.printStackTrace();
//        }
//    }

}


